package com.ErpCoreWeb.Database.Table;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Framework.CColumn;
import com.ErpCoreModel.Framework.CColumnEnumVal;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Framework.ColumnType;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreWeb.Common.EditObject;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class Add
 */
@WebServlet("/Database_Table_Add")
public class Add extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

	public CUser m_User = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Add() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
        m_User=(CUser)request.getSession().getAttribute("User");
        if (!m_User.IsRole("管理员"))
        {
        	try {
				response.getWriter().print("没有管理员权限！");
	        	response.getWriter().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	return ;
        }

    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("GetData"))
        {
            GetData();
            return ;
        }
        else if (Action.equalsIgnoreCase("PostData"))
        {
            PostData();
            return ;
        }
	}

    void GetData()
    {
		try {
			String sData = "";
			sData += String
					.format("{ \"id\": \"%s\",\"Name\":\"id\", \"Code\":\"id\", \"ColType\":\"GUID\", \"ColLen\":\"16\",\"AllowNull\":\"0\",\"IsSystem\":\"1\",\"DefaultValue\":\"\",\"ColDecimal\":\"\",\"Formula\":\"\",\"RefTable\":\"\",\"RefTableName\":\"\",\"RefCol\":\"\",\"RefColName\":\"\",\"RefShowCol\":\"\",\"RefShowColName\":\"\",\"EnumVal\":\"\", \"IsUnique\":\"1\" },",
							UUID.randomUUID().toString());
			sData += String
					.format("{ \"id\": \"%s\",\"Name\":\"创建时间\", \"Code\":\"Created\", \"ColType\":\"日期型\",\"ColLen\":\"8\", \"AllowNull\":\"1\",\"IsSystem\":\"1\",\"DefaultValue\":\"getdate()\",\"ColDecimal\":\"\",\"Formula\":\"\",\"RefTable\":\"\",\"RefTableName\":\"\",\"RefCol\":\"\",\"RefColName\":\"\",\"RefShowCol\":\"\",\"RefShowColName\":\"\",\"EnumVal\":\"\", \"IsUnique\":\"0\" },",
							UUID.randomUUID().toString());
			sData += String
					.format("{ \"id\": \"%s\",\"Name\":\"创建人\", \"Code\":\"Creator\", \"ColType\":\"GUID\",\"ColLen\":\"16\", \"AllowNull\":\"1\",\"IsSystem\":\"1\",\"DefaultValue\":\"\",\"ColDecimal\":\"\",\"Formula\":\"\",\"RefTable\":\"\",\"RefTableName\":\"\",\"RefCol\":\"\",\"RefColName\":\"\",\"RefShowCol\":\"\",\"RefShowColName\":\"\",\"EnumVal\":\"\", \"IsUnique\":\"0\" },",
							UUID.randomUUID().toString());
			sData += String
					.format("{ \"id\": \"%s\",\"Name\":\"修改时间\", \"Code\":\"Updated\", \"ColType\":\"日期型\",\"ColLen\":\"8\", \"AllowNull\":\"1\",\"IsSystem\":\"1\",\"DefaultValue\":\"getdate()\",\"ColDecimal\":\"\",\"Formula\":\"\",\"RefTable\":\"\",\"RefTableName\":\"\",\"RefCol\":\"\",\"RefColName\":\"\",\"RefShowCol\":\"\",\"RefShowColName\":\"\",\"EnumVal\":\"\", \"IsUnique\":\"0\" },",
							UUID.randomUUID().toString());
			sData += String
					.format("{ \"id\": \"%s\",\"Name\":\"修改人\", \"Code\":\"Updator\", \"ColType\":\"GUID\",\"ColLen\":\"16\", \"AllowNull\":\"1\",\"IsSystem\":\"1\",\"DefaultValue\":\"\",\"ColDecimal\":\"\",\"Formula\":\"\",\"RefTable\":\"\",\"RefTableName\":\"\",\"RefCol\":\"\",\"RefColName\":\"\",\"RefShowCol\":\"\",\"RefShowColName\":\"\",\"EnumVal\":\"\", \"IsUnique\":\"0\" }",
							UUID.randomUUID().toString());
			sData = "[" + sData + "]";
			String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}",
					sData, 5);

			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    void PostData()
    {
		try {
			String id = request.getParameter("id");
			String Name = request.getParameter("Name");
			String Code = request.getParameter("Code");
			String IsSystem = request.getParameter("IsSystem");
			String GridData = request.getParameter("GridData");

			CUser user = (CUser) request.getSession().getAttribute("User");

			if (Global.IsNullParameter(id) || Global.IsNullParameter(Name)
					|| Global.IsNullParameter(Code)) {
				response.getWriter().print("数据不完整！");
				return;
			} else {
				if (Global.GetCtx(this.getServletContext()).getTableMgr()
						.FindByName(Name) != null) {
					response.getWriter().print("相同名称的表已经存在！");
					return;
				}
				if (Global.GetCtx(this.getServletContext()).getTableMgr()
						.FindByCode(Code) != null) {
					response.getWriter().print("相同编码的表已经存在！");
					return;
				}

				CTable table = new CTable();
				table.Ctx = Global.GetCtx(this.getServletContext());
				table.setId(Util.GetUUID(id));
				table.setName(Name);
				table.setCode(Code);
				table.setIsSystem(IsSystem.equals("1") ? true : false);
				table.setIsFinish(true);
				table.setUpdator(user.getId());
				// 系统字段
				{
					CColumn col = new CColumn();
					col.Ctx = table.Ctx;
					col.setFW_Table_id(table.getId());
					col.setName("id");
					col.setCode("id");
					col.setColType(ColumnType.guid_type);
					col.setColLen(16);
					col.setAllowNull(false);
					col.setIsSystem(true);
					col.setIsUnique(true);
					col.setIsVisible(false);
					col.setIdx(0);
					col.setCreator(user.getId());
					table.getColumnMgr().AddNew(col);

					col = new CColumn();
					col.Ctx = table.Ctx;
					col.setFW_Table_id(table.getId());
					col.setName("创建时间");
					col.setCode("Created");
					col.setColType(ColumnType.datetime_type);
					col.setColLen(8);
					// col.DefaultValue = "getdate()";
					col.setAllowNull(true);
					col.setIsSystem(true);
					col.setIsUnique(false);
					col.setIsVisible(false);
					col.setIdx(1);
					col.setCreator(user.getId());
					table.getColumnMgr().AddNew(col);

					col = new CColumn();
					col.Ctx = table.Ctx;
					col.setFW_Table_id(table.getId());
					col.setName("创建者");
					col.setCode("Creator");
					col.setColType(ColumnType.ref_type);
					CTable tableUser = (CTable) Global
							.GetCtx(this.getServletContext()).getTableMgr()
							.FindByCode("B_User");
					UUID guidUid = Util.GetEmptyUUID();
					UUID guidUname = Util.GetEmptyUUID();
					if (tableUser != null) {
						col.setRefTable(tableUser.getId());
						CColumn colUid = tableUser.getColumnMgr().FindByCode(
								"id");
						col.setRefCol(colUid.getId());
						guidUid = col.getRefCol();
						CColumn colUname = tableUser.getColumnMgr().FindByCode(
								"name");
						col.setRefShowCol(colUname.getId());
						guidUname = col.getRefShowCol();
					}
					col.setColLen(16);
					// col.DefaultValue = "0";
					col.setAllowNull(true);
					col.setIsSystem(true);
					col.setIsUnique(false);
					col.setIsVisible(false);
					col.setIdx(2);
					col.setCreator(user.getId());
					table.getColumnMgr().AddNew(col);

					col = new CColumn();
					col.Ctx = table.Ctx;
					col.setFW_Table_id(table.getId());
					col.setName("修改时间");
					col.setCode("Updated");
					col.setColType(ColumnType.datetime_type);
					col.setColLen(8);
					// col.DefaultValue = "getdate()";
					col.setAllowNull(true);
					col.setIsSystem(true);
					col.setIsUnique(false);
					col.setIsVisible(false);
					col.setIdx(3);
					col.setCreator(user.getId());
					table.getColumnMgr().AddNew(col);

					col = new CColumn();
					col.Ctx = table.Ctx;
					col.setFW_Table_id(table.getId());
					col.setName("修改者");
					col.setCode("Updator");
					col.setColType(ColumnType.ref_type);
					if (tableUser != null) {
						col.setRefTable(tableUser.getId());
						col.setRefCol(guidUid);
						col.setRefShowCol(guidUname);
					}
					col.setColLen(16);
					// col.DefaultValue = "0";
					col.setAllowNull(true);
					col.setIsSystem(true);
					col.setIsUnique(false);
					col.setIsVisible(false);
					col.setIdx(4);
					col.setCreator(user.getId());
					table.getColumnMgr().AddNew(col);
				}
				// 自定义字段
				int iLastIdx = 4;
				String[] arr1 = GridData.split(";");
				for (String str1 : arr1) {
					if (str1.length() == 0)
						continue;
					iLastIdx++;

					String[] arr2 = str1.split(",");
					CColumn col = new CColumn();
					col.Ctx = table.Ctx;
					col.setFW_Table_id(table.getId());
					col.setId(Util.GetUUID(arr2[0]));
					col.setName(arr2[1]);
					col.setCode(arr2[2]);
					col.setColType(CColumn.ConvertStringToColType(arr2[3]));
					col.setColLen(Integer.valueOf(arr2[4]));
					col.setAllowNull((arr2[5].equals("1")) ? true : false);
					col.setIsSystem((arr2[6].equals( "1")) ? true : false);
					col.setIsUnique((arr2[17].equals( "1")) ? true : false);
					col.setIsVisible(true);
					col.setDefaultValue(arr2[7]);
					col.setColDecimal((arr2[8].length()>0) ? Integer
							.valueOf(arr2[8]) : 0);
					col.setFormula(arr2[9]);
					if (col.getColType() == ColumnType.ref_type) {
						col.setRefTable(Util.GetUUID(arr2[10]));
						col.setRefCol(Util.GetUUID(arr2[12]));
						col.setRefShowCol(Util.GetUUID(arr2[14]));
					}
					if (arr2[16].trim().length() > 0) {
						col.getColumnEnumValMgr().RemoveAll();
						String[] arrEnum = arr2[16].trim().split("/");
						for (int i = 0; i < arrEnum.length; i++) {
							String sEnumVal = arrEnum[i];
							CColumnEnumVal ev = new CColumnEnumVal();
							ev.Ctx = col.Ctx;
							ev.setFW_Column_id(col.getId());
							ev.setVal(sEnumVal);
							ev.setIdx(i);
							col.getColumnEnumValMgr().AddNew(ev);
						}
					}
					col.setIdx(iLastIdx);
					col.setCreator(user.getId());
					table.getColumnMgr().AddNew(col);
				}

				Global.GetCtx(this.getServletContext()).getTableMgr()
						.AddNew(table);

				if (!CTable.CreateDataTable(table)) {
					response.getWriter().print("创建表失败！");
					return;
				}
				if (!Global.GetCtx(this.getServletContext()).getTableMgr()
						.Save(true)) {
					response.getWriter().print("添加失败！");
					return;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
